package com.winhxd.b2c.product.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.context.CustomerUser;
import com.winhxd.b2c.common.context.UserContext;
import com.winhxd.b2c.common.domain.PagedList;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.condition.DistributorChannelTypeCondition;
import com.winhxd.b2c.common.domain.customer.vo.CustomerDistributorChannelTypeVO;
import com.winhxd.b2c.common.domain.customer.vo.CustomerDistributorTypeAndChannelVO;
import com.winhxd.b2c.common.domain.product.condition.ProductCondition;
import com.winhxd.b2c.common.domain.product.condition.ProductListQueryCondition;
import com.winhxd.b2c.common.domain.product.condition.ProductSaveOrUpdateCondition;
import com.winhxd.b2c.common.domain.product.condition.ProductSkuListCondition;
import com.winhxd.b2c.common.domain.product.condition.ProductSpuCondition;
import com.winhxd.b2c.common.domain.product.condition.ProductSpuListCondition;
import com.winhxd.b2c.common.domain.product.model.ProductAttribute;
import com.winhxd.b2c.common.domain.product.model.ProductAttributeOption;
import com.winhxd.b2c.common.domain.product.model.ProductBrand;
import com.winhxd.b2c.common.domain.product.model.ProductCategory;
import com.winhxd.b2c.common.domain.product.model.ProductPriceProgram;
import com.winhxd.b2c.common.domain.product.model.ProductPriceSku;
import com.winhxd.b2c.common.domain.product.model.ProductPriceSpu;
import com.winhxd.b2c.common.domain.product.model.ProductSku;
import com.winhxd.b2c.common.domain.product.model.ProductSpu;
import com.winhxd.b2c.common.domain.product.model.ProductSpuCategory;
import com.winhxd.b2c.common.domain.product.model.ProductSpuDetailImage;
import com.winhxd.b2c.common.domain.product.model.ProductSpuImage;
import com.winhxd.b2c.common.domain.product.model.ProductSpuTag;
import com.winhxd.b2c.common.domain.product.model.ProductSpuVideo;
import com.winhxd.b2c.common.domain.product.model.ProductSpuVoice;
import com.winhxd.b2c.common.domain.product.model.ProductTag;
import com.winhxd.b2c.common.domain.product.vo.*;
import com.winhxd.b2c.common.domain.search.dto.ProductSearchParam;
import com.winhxd.b2c.common.domain.search.dto.SearchResult;
import com.winhxd.b2c.common.domain.search.model.ProductDocument;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.customer.CustomerServiceClient;
import com.winhxd.b2c.common.feign.search.ProductSearchClient;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.product.dao.ProductAttributeMapper;
import com.winhxd.b2c.product.dao.ProductAttributeOptionMapper;
import com.winhxd.b2c.product.dao.ProductBrandMapper;
import com.winhxd.b2c.product.dao.ProductCategoryMapper;
import com.winhxd.b2c.product.dao.ProductPriceProgramMapper;
import com.winhxd.b2c.product.dao.ProductPriceSkuMapper;
import com.winhxd.b2c.product.dao.ProductPriceSpuMapper;
import com.winhxd.b2c.product.dao.ProductSkuMapper;
import com.winhxd.b2c.product.dao.ProductSpuCategoryMapper;
import com.winhxd.b2c.product.dao.ProductSpuDetailImageMapper;
import com.winhxd.b2c.product.dao.ProductSpuImageMapper;
import com.winhxd.b2c.product.dao.ProductSpuMapper;
import com.winhxd.b2c.product.dao.ProductSpuTagMapper;
import com.winhxd.b2c.product.dao.ProductSpuVideoMapper;
import com.winhxd.b2c.product.dao.ProductSpuVoiceMapper;
import com.winhxd.b2c.product.dao.ProductTagMapper;
import com.winhxd.b2c.product.service.ProductService;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author luosixiang
 */
@Service
public class ProductServiceImpl implements ProductService {

    private Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Autowired
    private ProductSpuMapper productSpuMapper;

    @Autowired
    private ProductSpuCategoryMapper productSpuCategoryMapper;

    @Autowired
    private ProductSpuTagMapper productSpuTagMapper;

    @Autowired
    private ProductTagMapper productServiceMapper;

    @Autowired
    private ProductSpuImageMapper productSpuImageMapper;

    @Autowired
    private ProductSpuVoiceMapper productSpuVoiceMapper;

    @Autowired
    private ProductSpuVideoMapper productSpuVideoMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    @Autowired
    private ProductAttributeMapper productAttributeMapper;

    @Autowired
    private ProductAttributeOptionMapper productAttributeOptionMapper;

    @Autowired
    private ProductSpuDetailImageMapper productSpuDetailImageMapper;

    @Autowired
    private ProductPriceProgramMapper productPriceProgramMapper;

    @Autowired
    private ProductPriceSpuMapper productPriceSpuMapper;

    @Autowired
    private ProductPriceSkuMapper productPriceSkuMapper;
    @Autowired
    private ProductBrandMapper productBrandMapper;

    @Autowired
    private CustomerServiceClient customerServiceClient;

    @Autowired
    private ProductSearchClient productSearchClient;

    @Override
    public PagedList<ProductListWebVO> findProductListByPage(ProductCondition condition) {
        logger.info("findProductList方法入参是：" + JsonUtil.toJSONString(condition));
        Page page = PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
        List<ProductListWebVO> productListWebVOList = productSpuMapper.selectByCondition(condition);
        PagedList<ProductListWebVO> pagedList = new PagedList<>();
        pagedList.setData(productListWebVOList);
        pagedList.setPageNo(condition.getPageNo());
        pagedList.setPageSize(condition.getPageSize());
        pagedList.setTotalRows(page.getTotal());
        return pagedList;
    }

    @Override
    public PagedList<ProductListForAssemblyWebVO> findProductListForAssemblyByPage(ProductCondition condition) {
        logger.info("findProductListForAssemblyByPage方法入参是：" + JsonUtil.toJSONString(condition));
        CustomerDistributorTypeAndChannelVO channelVO = new CustomerDistributorTypeAndChannelVO();

        //登录用户的渠道价格方案
        Long priceProgramId = null;

        //原译员工查询默认渠道
        if (condition.getCustomerId() == null){
            DistributorChannelTypeCondition cond = new DistributorChannelTypeCondition();
            cond.setChannelSign(1);
            List<CustomerDistributorChannelTypeVO> dataWithException = customerServiceClient.findDistributerChannelTypeList(cond).getDataWithException();
            if (CollectionUtils.isNotEmpty(dataWithException)){
                priceProgramId = dataWithException.get(0).getPriceTypeId();
            }
        }else {
            channelVO = customerServiceClient.getCustomerChannelById(condition.getCustomerId()).getDataWithException();
            priceProgramId = channelVO == null ? null : channelVO.getPriceTypeId();
        }

        //如果没有价格，提示用户“敬请期待”
        if(priceProgramId == null){
            throw new BusinessException(BusinessCode.CODE_800601);
        }
        condition.setPriceTypeId(priceProgramId);
        Page page = PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
        List<ProductListForAssemblyWebVO> voList = productSpuMapper.selectForAssemblyByCondition(condition);
        for (int k = 0; k < voList.size(); k++) {
            //拼装已选中的tag
            List<ProductTag> productTagList = new ArrayList<>();

            ProductTag productTag = new ProductTag();
            List<ProductTag> tagList = productServiceMapper.selectProductTagByModel(productTag);

            ProductSpuTag productSpuTag = new ProductSpuTag();
            productSpuTag.setSpuId(Long.valueOf(voList.get(k).getSpuId()));
            List<ProductSpuTag> spuTagList = productSpuTagMapper.selectByModel(productSpuTag);

            for (int i = 0; i < tagList.size(); i++) {
                for (int j = 0; j < spuTagList.size(); j++) {
                    if (tagList.get(i).getId().equals(spuTagList.get(j).getTagId())) {
                        productTagList.add(tagList.get(i));
                        break;
                    }
                }
            }
            voList.get(k).setProductTagList(productTagList);
        }

        PagedList<ProductListForAssemblyWebVO> pagedList = new PagedList<>();
        pagedList.setData(voList);
        pagedList.setPageNo(condition.getPageNo());
        pagedList.setPageSize(condition.getPageSize());
        pagedList.setTotalRows(page.getTotal());
        return pagedList;
    }

    @Override
    public List<ProductSpu> findProductList(ProductSpu model) {
        return productSpuMapper.selectByModel(model);
    }

    @Override
    public Integer modifyProduct(ProductSpu model) {
        return productSpuMapper.updateByPrimaryKeySelective(model);
    }

    @Override
    public Integer operateProducts(ProductCondition condition) {
        ProductSpu model = null;
        Integer count = 0;

        if (CollectionUtils.isEmpty(condition.getIds()) && condition.getSpuId() != null){
            List ids = new ArrayList();
            ids.add(condition.getSpuId());
            condition.setIds(ids);
        }

        //上架
        if (ProductCondition.OPERATE.UP.getCode().equals(condition.getOperate()) || (condition.getSaleStatus() != null && condition.getSaleStatus() == 0)){
            model = new ProductSpu();
            model.setSaleStatus(1);
            model.setSaleTime(new Date());

        //下架
        }else if (ProductCondition.OPERATE.DOWN.getCode().equals(condition.getOperate()) || (condition.getSaleStatus() != null && condition.getSaleStatus() == 1)){
            model = new ProductSpu();
            model.setSaleStatus(0);

        //批量删除
        }else if (ProductCondition.OPERATE.DELETE.getCode().equals(condition.getOperate())){
            List<Long> ids = condition.getIds();
            if (CollectionUtils.isNotEmpty(ids)){
                ProductCondition cond = new ProductCondition();
                cond.setSaleStatus((byte) 1);
                cond.setIds(ids);
                Integer cut = productSpuMapper.countByCondition(cond);
                if (cut > 0){
                    throw new BusinessException(BusinessCode.CODE_810200);
                }
            }
            model = new ProductSpu();
            model.setStatus(0);

        //单条删除
        }else if (condition.getStatus() != null && condition.getStatus() == 1){

            model = new ProductSpu();
            model.setStatus(0);

        //还原
        }else if (ProductCondition.OPERATE.RESTORE.getCode().equals(condition.getOperate()) || (condition.getStatus() != null && condition.getStatus() == 0)){
            model = new ProductSpu();
            model.setStatus(1);
            model.setStock(0L);
            //sku库存也要置为0
            ProductSku sku = new ProductSku();
            sku.setSpuIdList(condition.getIds());
            sku.setStock((long) 0);
            if (CollectionUtils.isNotEmpty(condition.getIds())){
                productSkuMapper.batchUpdateBySpuIds(sku);
            }
            //只有下架商品能删除，也就是说回收站都是下架商品，所以还原后不必置为下架
//            model.setSaleStatus(0);
        }
        if (CollectionUtils.isNotEmpty(condition.getIds())){
            count = productSpuMapper.batchUpdateByPrimaryKeySelective(model, condition.getIds());
        }
        //整理es需要的数据
        List<Long> ids = condition.getIds();
        logger.info("操作es数据的商品id："+ids);
        List<ProductVO> productVOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ids)){
            for (int i = 0; i < ids.size(); i++) {
                ProductSaveOrUpdateCondition cond = new ProductSaveOrUpdateCondition();
                Long spuId = ids.get(i);
                cond.setSpuId(spuId);
                cond.setOpType("2");
                ProductVO vo = this.toSave(cond);
                List<ProductTag> selectedTagList = vo.getProductTagList().stream().filter(v -> v.getSelected() == 1).collect(Collectors.toList());
                vo.setProductTagList(selectedTagList);

                List<ProductAttributeVO> productAttributeList = vo.getProductAttributeList();
                productAttributeList.forEach(attr -> {
                    List<ProductAttributeOptionVO> optionList = attr.getAttributeOptionList();
                    List<ProductAttributeOptionVO> selectedOptionList = optionList.stream().filter(o -> o.getSelected() == 1).collect(Collectors.toList());
                    attr.setAttributeOptionList(selectedOptionList);
                });

                ProductPriceSpu productPriceSpu = new ProductPriceSpu();
                productPriceSpu.setSpuId(spuId);
                List<ProductPriceSpu> productPriceSpus = productPriceSpuMapper.selectByModel(productPriceSpu);
                vo.setProductPriceSpuList(productPriceSpus);

                ProductPriceSku productPriceSku = new ProductPriceSku();
                productPriceSku.setSpuId(spuId);
                List<ProductPriceSku> productPriceSkus = productPriceSkuMapper.selectByModel(productPriceSku);
                vo.setProductPriceSkuList(productPriceSkus);

                //给es的SalesVolume是最终销量（初始化销量+真实销量）
                for (int j = 0; j < vo.getProductSkuList().size(); j++) {
                    vo.getProductSkuList().get(j).setSalesVolume(vo.getProductSkuList().get(j).getInitSalesVolume()+vo.getProductSkuList().get(j).getSalesVolume());
                }

                productVOList.add(vo);
            }
        }

        //上架
        if (ProductCondition.OPERATE.UP.getCode().equals(condition.getOperate()) || (condition.getSaleStatus() != null && condition.getSaleStatus() == 0)){
            productSearchClient.importProduct(productVOList);

            //下架
        }else if (ProductCondition.OPERATE.DOWN.getCode().equals(condition.getOperate()) || (condition.getSaleStatus() != null && condition.getSaleStatus() == 1)){
            productSearchClient.deleteSpuList(ids);

        }

        return count;
    }

    @Transactional(rollbackFor = {BusinessException.class, Exception.class},isolation = Isolation.READ_COMMITTED)
    @Override
    public Integer saveProduct(ProductVO condition) {
        Long spuId = condition.getSpuId();
        //商品总库存
        Long spuStock = 0L;
        //商品总初始销量
        Long spuInitSalesVolume = 0L;
        ProductSpu model = new ProductSpu();
        //全部的价格方案
        List<ProductPriceProgram> priceProgramList = productPriceProgramMapper.selectAll();

        //校验前端参数
        this.checkParams(condition);
        //新增
        if (spuId == null || spuId == 0){
            //新增时，校验货号
            ProductCondition cond = new ProductCondition();
            cond.setSpuCode(condition.getSpuCode());
            Integer count = productSpuMapper.countByCondition(cond);
            if (count > 0){
                throw new BusinessException(BusinessCode.CODE_810601);
            }
            model.setSpuCode(condition.getSpuCode());
            model.setBrandId(condition.getBrandId());
            model.setBrandName(condition.getBrandName());
            model.setSpuName(condition.getSpuName());
            model.setSubheadName(condition.getSubheadName());
            model.setRealSalesVolume(0L);
            model.setGuidePrice(condition.getGuidePrice());
            model.setStatus(1);
            model.setSaleStatus(0);

            model.setCreatedBy(condition.getUserName());
            model.setCreatedTime(new Date());
            productSpuMapper.insertSelective(model);
            spuId = model.getId();

            //添加spu价格方案
            for (ProductPriceProgram priceProgram : priceProgramList) {
                ProductPriceSpu priceSpu = new ProductPriceSpu();
                priceSpu.setBrandId(condition.getBrandId());
                priceSpu.setPriceProgramId(priceProgram.getId());
                priceSpu.setSpuId(spuId);
                priceSpu.setSettlementPrice(condition.getGuidePrice());
                priceSpu.setFirstIncome(BigDecimal.ZERO);
                priceSpu.setFirstPoint(0);
                priceSpu.setSecondIncome(BigDecimal.ZERO);
                priceSpu.setSecondPoint(0);
                priceSpu.setMemberIncome(BigDecimal.ZERO);
                priceSpu.setMemberPoint(0);
                priceSpu.setUniquePriceidSpuid(priceProgram.getId()+"_"+spuId);
                productPriceSpuMapper.insertSelective(priceSpu);
            }
        //修改
        }else {
            model = productSpuMapper.selectByPrimaryKey(spuId);

            model.setModifiedBy(condition.getUserName());
            model.setModifiedTime(new Date());

            //修改时，校验货号
            ProductCondition cond = new ProductCondition();
            cond.setSpuCode(condition.getSpuCode());
            cond.setSpuId(spuId);
            Integer count = productSpuMapper.countByCondition(cond);
            if (count > 0){
                throw new BusinessException(BusinessCode.CODE_810601);
            }

            model.setSpuCode(condition.getSpuCode());
            model.setSpuName(condition.getSpuName());
            model.setBrandId(condition.getBrandId());
            model.setBrandName(condition.getBrandName());
            model.setSubheadName(condition.getSubheadName());
            model.setGuidePrice(condition.getGuidePrice());

            //修改的话，先删除之前的关联表关系，后续直接添加
            //删除该商品的分类信息
            productSpuCategoryMapper.deleteBySpuId(spuId);
            //删除该商品的服务信息
            productSpuTagMapper.deleteBySpuId(spuId);
            //删除该商品的图片信息
            productSpuImageMapper.deleteBySpuId(spuId);
            //删除该商品的视频信息
            productSpuVideoMapper.deleteBySpuId(spuId);
            //删除该商品的音频信息
            productSpuVoiceMapper.deleteBySpuId(spuId);
            //删除该商品的详情图片信息
            productSpuDetailImageMapper.deleteBySpuId(spuId);
        }

        //保存新的分类信息
        List<ProductCategoryGroupVO> categoryGroupList = condition.getProductCategoryGroupList();
        for (ProductCategoryGroupVO productCategoryGroupVO : categoryGroupList) {
            ProductSpuCategory spuCategory = new ProductSpuCategory();
            spuCategory.setSpuId(spuId);
            spuCategory.setCategoryOneId(Long.valueOf(productCategoryGroupVO.getCategoryOneId()));
            spuCategory.setCategoryTwoId(Long.valueOf(productCategoryGroupVO.getCategoryTwoId()));
            spuCategory.setSort(productCategoryGroupVO.getSort());
            productSpuCategoryMapper.insertSelective(spuCategory);
        }

        //保存新的服务信息
        List<ProductTag> serviceList = condition.getProductTagList();
        for (ProductTag productTag : serviceList) {
            if (productTag.getSelected() == 1) {
                ProductSpuTag proService = new ProductSpuTag();
                proService.setSpuId(spuId);
                proService.setTagId(productTag.getId());
                productSpuTagMapper.insertSelective(proService);
            }
        }

        //保存新的图片信息
        List<ProductSpuImage> imageList = condition.getProductSpuImageList();
        for (ProductSpuImage productSpuImage : imageList) {
            ProductSpuImage spuImage = new ProductSpuImage();
            spuImage.setSpuId(spuId);
            spuImage.setImageUrl(productSpuImage.getImageUrl());
            spuImage.setSort(productSpuImage.getSort());
            productSpuImageMapper.insertSelective(spuImage);
        }

        //保存新的视频信息
        List<ProductSpuVideo> videoList = condition.getProductSpuVideoList();
        for (ProductSpuVideo video : videoList) {
            ProductSpuVideo spuVideo = new ProductSpuVideo();
            spuVideo.setSpuId(spuId);
            spuVideo.setVideoName(video.getVideoName());
            spuVideo.setVideoUrl(video.getVideoUrl());
            spuVideo.setFileId(video.getFileId());
            spuVideo.setVideoDuration(video.getVideoDuration());
            spuVideo.setCoverFilePath(video.getCoverFilePath());
            productSpuVideoMapper.insertSelective(spuVideo);
        }

        //保存新的音频信息
        List<ProductSpuVoice> spuVoiceList = condition.getProductSpuVoiceList();
        for (ProductSpuVoice productSpuVoice : spuVoiceList) {
            ProductSpuVoice spuVoice = new ProductSpuVoice();
            spuVoice.setSpuId(spuId);
            spuVoice.setFileName(productSpuVoice.getFileName());
            spuVoice.setVoiceName(productSpuVoice.getVoiceName());
            spuVoice.setVoiceUrl(productSpuVoice.getVoiceUrl());
            spuVoice.setSort(productSpuVoice.getSort());
            productSpuVoiceMapper.insertSelective(spuVoice);
        }
        //保存新的详情图片信息
        List<ProductSpuDetailImage> spuDetailImageList = condition.getProductSpuDetailImageList();
        for (ProductSpuDetailImage productSpuDetailImage : spuDetailImageList) {
            ProductSpuDetailImage spuDetailImage = new ProductSpuDetailImage();
            spuDetailImage.setSpuId(spuId);
            spuDetailImage.setImageUrl(productSpuDetailImage.getImageUrl());
            spuDetailImage.setSort(productSpuDetailImage.getSort());
            productSpuDetailImageMapper.insertSelective(spuDetailImage);
        }

        //属性值是生成sku用的，不用保存，但是要回显
        //保存sku信息
        List<ProductSku> skuList = condition.getProductSkuList();
        for (ProductSku productSku : skuList) {

            ProductSku sku = new ProductSku();
            //编辑
            if (productSku.getId() != null && !productSku.getId().equals(0L)) {
                sku = productSkuMapper.selectByPrimaryKey(productSku.getId());

                sku.setUpdatedBy(condition.getUserName());
                sku.setUpdatedTime(new Date());
                // 根据款号查询是否有相同款号存在
                ProductSku skuModel3 = new ProductSku();
                skuModel3.setSkuStyleCode(productSku.getSkuStyleCode());
                skuModel3.setSpuId(spuId);
                Integer count3 = productSkuMapper.countByCondition(skuModel3);
                if (count3 > 0){
                    throw new BusinessException(BusinessCode.CODE_810602);
                }

                //修改时，校验款号或sku唯一
                ProductSku skuModel = new ProductSku();
                if (productSku.getSizeAttributeOptionId() == null){
                    // 修改后的 ruleCode
                    sku.setRuleCode(productSku.getSkuStyleCode());
                    skuModel.setRuleCode(productSku.getSkuStyleCode());
                }else{
                    // 修改后的 ruleCode
                    sku.setRuleCode(productSku.getSkuStyleCode()+"_"+productSku.getSizeAttributeOptionId());
                    skuModel.setRuleCode(productSku.getSkuStyleCode()+"_"+productSku.getSizeAttributeOptionId());
                }
                skuModel.setId(productSku.getId());
                Integer count = productSkuMapper.countByCondition(skuModel);
                if (count > 0){
                    throw new BusinessException(BusinessCode.CODE_810602);
                }

                //修改时，校验sku唯一
                ProductSku skuModel2 = new ProductSku();
                //修改后的 SkuCode
                if (productSku.getSizeAttributeOptionId() == null){
                    skuModel2.setSkuCode(spuId+"_"+productSku.getColorAttributeOptionId()+"_"+productSku.getSizeAttributeOptionId());
                    sku.setSkuCode(spuId + "_" + productSku.getColorAttributeOptionId());
                }else{
                    skuModel2.setSkuCode(spuId+"_"+productSku.getColorAttributeOptionId()+"_"+productSku.getSizeAttributeOptionId());
                    sku.setSkuCode(spuId + "_" + productSku.getColorAttributeOptionId() +"_"+ productSku.getSizeAttributeOptionId());
                }

                skuModel2.setId(productSku.getId());
                Integer count2 = productSkuMapper.countByCondition(skuModel2);
                if (count2 > 0){
                    throw new BusinessException(BusinessCode.CODE_810603);
                }

                //新增
            } else {

                // 根据款号查询是否有相同款号存在
                ProductSku skuModel3 = new ProductSku();
                skuModel3.setSkuStyleCode(productSku.getSkuStyleCode());
                skuModel3.setSpuId(spuId);
                Integer count3 = productSkuMapper.countByCondition(skuModel3);
                if (count3 > 0){
                    throw new BusinessException(BusinessCode.CODE_810602);
                }

                //新增时，校验款号或sku唯一
                ProductSku skuModel = new ProductSku();
                //sku唯一索引:款号_SizeId
                if (productSku.getSizeAttributeOptionId() == null){
                    sku.setRuleCode(productSku.getSkuStyleCode());
                    skuModel.setRuleCode(productSku.getSkuStyleCode());
                }else{
                    sku.setRuleCode(productSku.getSkuStyleCode()+"_"+productSku.getSizeAttributeOptionId());
                    skuModel.setRuleCode(productSku.getSkuStyleCode()+"_"+productSku.getSizeAttributeOptionId());
                }
                Integer count = productSkuMapper.countByCondition(skuModel);
                if (count > 0){
                    throw new BusinessException(BusinessCode.CODE_810602);
                }
                //新增时，校验sku唯一
                ProductSku skuModel2 = new ProductSku();
                //商品编码，sku唯一索引:spuId_ColorId_SizeId
                if (productSku.getSizeAttributeOptionId() == null){
                    skuModel2.setSkuCode(spuId+"_"+productSku.getColorAttributeOptionId());
                    sku.setSkuCode(spuId + "_" + productSku.getColorAttributeOptionId());
                }else{
                    skuModel2.setSkuCode(spuId+"_"+productSku.getColorAttributeOptionId()+"_"+productSku.getSizeAttributeOptionId());
                    sku.setSkuCode(spuId + "_" + productSku.getColorAttributeOptionId() +"_"+ productSku.getSizeAttributeOptionId());
                }

                Integer count2 = productSkuMapper.countByCondition(skuModel2);
                if (count2 > 0){
                    throw new BusinessException(BusinessCode.CODE_810603);
                }

                sku.setSpuId(spuId);
                //1单个sku，2组合sku；目前默认单个sku
                sku.setSkuType((byte) 1);
                //初始化字段值
                sku.setSalesVolume(0L);
                sku.setStatus(1);

                //颜色属性id，应该是固定的
                sku.setColorAttributeId(productSku.getColorAttributeId());
                //颜色属性值id
                sku.setColorAttributeOptionId(productSku.getColorAttributeOptionId());
                //尺寸属性id，应该是固定的
                sku.setSizeAttributeId(productSku.getSizeAttributeId());
                //尺寸属性值id
                sku.setSizeAttributeOptionId(productSku.getSizeAttributeOptionId());


                sku.setCreatedBy(condition.getUserName());
                sku.setCreatedTime(new Date());
            }
            //sku的指导价暂且为商品的指导价,spu改了价格，sku也要改
            sku.setGuidePrice(condition.getGuidePrice());
            //以下是可编辑的sku属性
            //款号
            sku.setSkuStyleCode(productSku.getSkuStyleCode());
            //图片
            sku.setImageUrl(productSku.getImageUrl());
            //重量
            sku.setWeight(productSku.getWeight());
            //库存量
            if (productSku.getStock() == null){
                sku.setStock(0L);
            }else{
                sku.setStock(productSku.getStock());
            }
            //初始销量
            if (productSku.getInitSalesVolume() == null){
                sku.setInitSalesVolume(0L);
            }else{
                sku.setInitSalesVolume(productSku.getInitSalesVolume());
            }
            //计算商品总库存
            if (productSku.getStock() != null){
                spuStock += productSku.getStock();
            }
            //计算商品总初始销量
            if (productSku.getInitSalesVolume() != null){
                spuInitSalesVolume += productSku.getInitSalesVolume();
            }

            if (productSku.getId() != null && !productSku.getId().equals(0L)) {
                productSkuMapper.updateByPrimaryKeySelective(sku);
            } else {
                productSkuMapper.insertSelective(sku);
                Long skuId = sku.getId();

                //添加sku价格方案
                for (ProductPriceProgram priceProgram : priceProgramList) {
                    ProductPriceSpu productPriceSpu = null;
                    ProductPriceSpu spuPrice = new ProductPriceSpu();
                    spuPrice.setPriceProgramId(priceProgram.getId());
                    spuPrice.setSpuId(spuId);
                    List<ProductPriceSpu> priceSpuList = productPriceSpuMapper.selectByModel(spuPrice);
                    if (CollectionUtils.isNotEmpty(priceSpuList)){
                        productPriceSpu = priceSpuList.get(0);
                    }else {
                        throw new BusinessException(BusinessCode.CODE_810604);
                    }

                    ProductPriceSku priceSku = new ProductPriceSku();
                    priceSku.setBrandId(condition.getBrandId());
                    priceSku.setPriceProgramId(priceProgram.getId());
                    priceSku.setSpuId(spuId);
                    priceSku.setSkuId(skuId);
                    priceSku.setSettlementPrice(productPriceSpu.getSettlementPrice());
                    priceSku.setFirstIncome(productPriceSpu.getFirstIncome());
                    priceSku.setFirstPoint(productPriceSpu.getFirstPoint());
                    priceSku.setSecondIncome(productPriceSpu.getSecondIncome());
                    priceSku.setSecondPoint(productPriceSpu.getSecondPoint());
                    priceSku.setMemberIncome(productPriceSpu.getMemberIncome());
                    priceSku.setMemberPoint(productPriceSpu.getMemberPoint());
                    priceSku.setUniquePriceidSpuidSkuid(priceProgram.getId()+"_"+spuId+"_"+skuId);
                    productPriceSkuMapper.insertSelective(priceSku);
                }
            }
        }

        //给商品总库存赋值
        model.setStock(spuStock);
        model.setInitSalesVolume(spuInitSalesVolume);
        int i = productSpuMapper.updateByPrimaryKeySelective(model);

        return i;
    }

    @Override
    public ProductVO toSave(ProductSaveOrUpdateCondition condition) {

        Long spuId = condition.getSpuId();

        ProductVO productVO = new ProductVO();

        //品牌列表
        List<ProductBrand> productBrandList = productBrandMapper.selectAllBrand();

        //一级分类
        ProductCategory productCategory = new ProductCategory();
        productCategory.setLevel((byte) 1);
        List<ProductCategory> categoryOneList = productCategoryMapper.selectByModel(productCategory);

        //服务列表
        ProductTag productTag = new ProductTag();
        productTag.setStatus(1);
        List<ProductTag> productTagList = productServiceMapper.selectProductTagByModel(productTag);

        //回显属性列表
        List<ProductAttributeVO> productAttributeVOList = new ArrayList<>();
        //查询所有属性（就两个）
        ProductAttribute productAttribute = new ProductAttribute();
        List<ProductAttribute> attributeList = productAttributeMapper.selectProductAttributeByModel(productAttribute);
        //把属性放进VO
        for (ProductAttribute attribute : attributeList) {
            //拼装属性VO
            ProductAttributeVO attributeVO = new ProductAttributeVO();
            attributeVO.setAttributeId(attribute.getId());
            attributeVO.setAttributeName(attribute.getAttributeName());
            List<ProductAttributeOption> attributeOptionList = productAttributeOptionMapper.selectAttributeOptionByAttributeId(attribute.getId());
            List<ProductAttributeOptionVO> optionVOList = new ArrayList<>();
            for (ProductAttributeOption productAttributeOption : attributeOptionList) {
                //拼装属性值VO
                ProductAttributeOptionVO attributeOptionVO = new ProductAttributeOptionVO();
                attributeOptionVO.setId(productAttributeOption.getId());
                attributeOptionVO.setAttributeId(productAttributeOption.getAttributeId());
                attributeOptionVO.setOptionValue(productAttributeOption.getOptionValue());
                attributeOptionVO.setSortNo(productAttributeOption.getSortNo());
                optionVOList.add(attributeOptionVO);
            }
            attributeVO.setAttributeOptionList(optionVOList);
            productAttributeVOList.add(attributeVO);
        }

        //初始化一级分类列表，服务列表，属性值列表
        productVO.setProductBrandList(productBrandList);
        productVO.setProductCategoryOneList(categoryOneList);
        productVO.setProductTagList(productTagList);
        productVO.setProductAttributeList(productAttributeVOList);
        //新增页面
        if ("1".equals(condition.getOpType())){

            //新增的话，以上的值就够了

            //编辑页面
        } else if ("2".equals(condition.getOpType())){

            //回显商品信息
            ProductSpu productSpu = productSpuMapper.selectByPrimaryKey(spuId);
            productVO.setSpuId(spuId);
            productVO.setBrandId(productSpu.getBrandId());
            productVO.setBrandName(productSpu.getBrandName());
            productVO.setSpuCode(productSpu.getSpuCode());
            productVO.setSpuName(productSpu.getSpuName());
            productVO.setSubheadName(productSpu.getSubheadName());
            productVO.setGuidePrice(productSpu.getGuidePrice());
            productVO.setSaleTime(productSpu.getSaleTime());

            //回显分类列表
            List<ProductCategoryGroupVO> spuCategoryList = productSpuCategoryMapper.selectGroupBySpuId(spuId);
            productVO.setProductCategoryGroupList(spuCategoryList);

            //回显服务列表
            ProductSpuTag productSpuTag = new ProductSpuTag();
            productSpuTag.setSpuId(spuId);
            List<ProductSpuTag> spuServiceList = productSpuTagMapper.selectByModel(productSpuTag);
            for (int i = 0; i < productTagList.size(); i++) {
                for (int j = 0; j < spuServiceList.size(); j++) {
                    if (productTagList.get(i).getId().equals(spuServiceList.get(j).getTagId())) {
                        //把服务置为选中
                        productTagList.get(i).setSelected(1);
                        break;
                    }
                }
            }

            //回显图片列表
            ProductSpuImage spuImage = new ProductSpuImage();
            spuImage.setSpuId(spuId);
            List<ProductSpuImage> spuImageList = productSpuImageMapper.selectByModel(spuImage);
            productVO.setProductSpuImageList(spuImageList);

            //回显视频列表
            ProductSpuVideo spuVideo = new ProductSpuVideo();
            spuVideo.setSpuId(spuId);
            List<ProductSpuVideo> spuVideoList = productSpuVideoMapper.selectByModel(spuVideo);
            productVO.setProductSpuVideoList(spuVideoList);

            //回显音频列表
            ProductSpuVoice spuVoice = new ProductSpuVoice();
            spuVoice.setSpuId(spuId);
            List<ProductSpuVoice> spuVoiceList = productSpuVoiceMapper.selectByModel(spuVoice);
            productVO.setProductSpuVoiceList(spuVoiceList);

            //回显SKU列表
            ProductSku sku = new ProductSku();
            sku.setSpuId(spuId);
            List<ProductSku> skuList = productSkuMapper.selectByModel(sku);

            //回显选中的属性值列表
            for (int i = 0; i < productAttributeVOList.size(); i++) {
                List<ProductAttributeOptionVO> attributeOptionList = productAttributeVOList.get(i).getAttributeOptionList();
                for (int j = 0; j < attributeOptionList.size(); j++) {
                    for (int k = 0; k < skuList.size(); k++) {
                        //如果属性列表中的id与sku中的id相同，则为选中
                        if ((attributeOptionList.get(j).getAttributeId().equals(skuList.get(k).getColorAttributeId())
                                && attributeOptionList.get(j).getId().equals(skuList.get(k).getColorAttributeOptionId()))) {
                            attributeOptionList.get(j).setSelected(1);
                            skuList.get(k).setColorValue(attributeOptionList.get(j).getOptionValue());
                        }
                        if ((attributeOptionList.get(j).getAttributeId().equals(skuList.get(k).getSizeAttributeId())
                                && attributeOptionList.get(j).getId().equals(skuList.get(k).getSizeAttributeOptionId()))) {
                            attributeOptionList.get(j).setSelected(1);
                            skuList.get(k).setSizeValue(attributeOptionList.get(j).getOptionValue());
                        }
                    }
                }
            }

            productVO.setProductSkuList(skuList);
            //回显商品详情图片列表
            ProductSpuDetailImage spuDetailImage = new ProductSpuDetailImage();
            spuDetailImage.setSpuId(spuId);
            List<ProductSpuDetailImage> spuDetailImageList = productSpuDetailImageMapper.selectByModel(spuDetailImage);
            productVO.setProductSpuDetailImageList(spuDetailImageList);

        }

        return productVO;
    }
    /**
     * @description 保存商品前校验参数
     * @auther yuluyuan
     * @date: 2019/1/13 15:18
     * @param: [condition]
     * @return: void
     */
    private void checkParams(ProductVO condition){

        List<ProductCategoryGroupVO> productCategoryGroupList = condition.getProductCategoryGroupList();
        if (CollectionUtils.isEmpty(productCategoryGroupList)){
            throw new BusinessException(BusinessCode.CODE_810600);
        }
        String spuCode = condition.getSpuCode();
        if (spuCode.isEmpty()){
            throw new BusinessException(BusinessCode.CODE_810600);
        }
        String spuName = condition.getSpuName();
        if (spuName.isEmpty() || spuName.length() > 25){
            throw new BusinessException(BusinessCode.CODE_810600);
        }
        BigDecimal guidePrice = condition.getGuidePrice();
        if (guidePrice == null || guidePrice.compareTo(BigDecimal.ZERO) <= 0){
            throw new BusinessException(BusinessCode.CODE_810600);
        }
        List<ProductTag> productTagList = condition.getProductTagList();
        List<ProductTag> collect = productTagList.stream().filter(s -> s.getSelected() == 1).collect(Collectors.toList());
        if (collect.size() > 3){
            throw new BusinessException(BusinessCode.CODE_810600);
        }
        List<ProductSpuImage> productSpuImageList = condition.getProductSpuImageList();
        if (productSpuImageList.size() < 1 || productSpuImageList.size() > 6){
            throw new BusinessException(BusinessCode.CODE_810600);
        }
        List<ProductSpuVoice> productSpuVoiceList = condition.getProductSpuVoiceList();
        if (productSpuVoiceList.size() > 6){
            throw new BusinessException(BusinessCode.CODE_810600);
        }
        List<ProductSpuDetailImage> productSpuDetailImageList = condition.getProductSpuDetailImageList();
        if (productSpuDetailImageList.size() > 20){
            throw new BusinessException(BusinessCode.CODE_810600);
        }
        List<ProductSku> productSkuList = condition.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)){
            throw new BusinessException(BusinessCode.CODE_810600);
        }
    }

    @Override
    public Map<Long, ProductSpuSimpleVO> findSimpleProductList(ProductSpuListCondition condition) {
        if (CollectionUtils.isEmpty(condition.getSpuIdList())) {
            throw new BusinessException(BusinessCode.CODE_810501);
        }
        CustomerDistributorTypeAndChannelVO channelVO = customerServiceClient.getCustomerChannelById(condition.getCustomerId()).getDataWithException();
        //登录用户的渠道价格方案
        Long priceProgramId = channelVO == null ? null : channelVO.getPriceTypeId();
        //如果没有价格，提示用户“敬请期待”
        if(priceProgramId == null){
            throw new BusinessException(BusinessCode.CODE_800601);
        }
        Map<Long, ProductSpuSimpleVO> longProductSpuSimpleVOMap = productSpuMapper.selectSimpleProductList(priceProgramId, condition.getSpuIdList());
        return longProductSpuSimpleVOMap;
    }

    @Override
    public Map<Long, ProductShopcarSkuVO> findShopcarSkuList(ProductSkuListCondition condition) {
        if (CollectionUtils.isEmpty(condition.getSkuIdList())) {
            throw new BusinessException(BusinessCode.CODE_810401);
        }

        CustomerDistributorTypeAndChannelVO channelVO = customerServiceClient.getCustomerChannelById(condition.getCustomerId()).getDataWithException();
        //登录用户的渠道价格方案
        Long priceProgramId = channelVO == null ? null : channelVO.getPriceTypeId();
        //如果没有价格，提示用户“敬请期待”
        if(priceProgramId == null){
            throw new BusinessException(BusinessCode.CODE_800601);
        }
        Map<Long, ProductShopcarSkuVO> longProductSpuSimpleVOMap = productSkuMapper.selectShopcarSkuList(priceProgramId, condition.getSkuIdList());
        return longProductSpuSimpleVOMap;
    }

    @Override
    public ProductSpuDetailVO getProductDetail(ProductSpuCondition condition) {
        Long spuId = condition.getSpuId();
        CustomerDistributorTypeAndChannelVO channel = customerServiceClient.getCustomerChannelById(condition.getCustomerId()).getDataWithException();
        //登录用户的渠道价格方案
        Long priceProgramId = channel == null ? null : channel.getPriceTypeId();
        //查询分享用户的渠道价格方案
        if(priceProgramId == null){
            channel = customerServiceClient.getCustomerChannelById(condition.getShareCustomerId()).getDataWithException();
            priceProgramId = channel == null ? null : channel.getPriceTypeId();
        }
        //如果没有价格，提示用户“敬请期待”
        if(priceProgramId == null){
            throw new BusinessException(BusinessCode.CODE_800601);
        }
        //商品基本信息
        ProductSpuDetailVO spuDetail = productSpuMapper.selectSpuInnerJoinPriceSpu(spuId, priceProgramId);
        if(spuDetail == null){
            throw new BusinessException(BusinessCode.CODE_800602);
        }

        //商品图片列表
        ProductSpuImage spuImage = new ProductSpuImage();
        spuImage.setSpuId(spuId);
        List<ProductSpuImage> spuImageList = productSpuImageMapper.selectByModel(spuImage);
        spuDetail.setProductSpuImageList(spuImageList);
        //商品视频列表，目前只支持一个
        ProductSpuVideo spuVideo = new ProductSpuVideo();
        spuVideo.setSpuId(spuId);
        List<ProductSpuVideo> spuVideoList = productSpuVideoMapper.selectByModel(spuVideo);
        spuDetail.setProductSpuVideoList(spuVideoList);
        //商品音频列表
        ProductSpuVoice spuVoice = new ProductSpuVoice();
        spuVoice.setSpuId(spuId);
        List<ProductSpuVoice> spuVoiceList = productSpuVoiceMapper.selectByModel(spuVoice);
        spuDetail.setProductSpuVoiceList(spuVoiceList);
        //商品服务（标签）列表
        List<ProductTag> tagList = productSpuTagMapper.selectProductTagLeftJoinProductSpuTagBySpuId(spuId);
        spuDetail.setProductTagList(tagList);
        //商品详情列表
        ProductSpuDetailImage spuDetailImage = new ProductSpuDetailImage();
        spuDetailImage.setSpuId(spuId);
        List<ProductSpuDetailImage> spuDetailImageList = productSpuDetailImageMapper.selectByModel(spuDetailImage);
        spuDetail.setProductSpuDetailImageList(spuDetailImageList);
        //商品SKU列表
        List<ProductSkuPriceVO> skuList = productPriceSkuMapper.selectSkuPriceBySpuId(spuId, priceProgramId);
        spuDetail.setProductSkuList(skuList);
        //查询所有属性（颜色、尺寸等）
        List<ProductAttributeVO> productAttributeList = productAttributeMapper.selectProductAttributeVOList();
        if(CollectionUtils.isEmpty(productAttributeList)){
            throw new BusinessException(BusinessCode.CODE_800601);
        }
        if(productAttributeList.size() != 2){
            throw new BusinessException(BusinessCode.CODE_800603);
        }
        spuDetail.setProductAttributeList(productAttributeList);

        //查询颜色属性值（option）及库存
        ProductAttributeVO colorAttribute = productAttributeList.get(0);
        ProductAttributeVO sizeAttribute = productAttributeList.get(1);
        List<ProductAttributeOptionVO> colorOptionList = productAttributeOptionMapper.selectColorStockBySpuId(spuId);
        colorAttribute.setAttributeOptionList(colorOptionList);
        //查询尺寸属性值（option）及库存
        List<ProductAttributeOptionVO> sizeOptionList = productAttributeOptionMapper.selectSizeStockBySpuId(spuId);
        if(sizeOptionList == null){
            sizeOptionList = new ArrayList<>();
        }
        sizeAttribute.setAttributeOptionList(sizeOptionList);

        spuDetail.setSkuSimpleDesc("");
        //未选择属性时，显示“颜色 尺寸”
        for(ProductAttributeVO attribute : productAttributeList){
            spuDetail.setSkuSimpleDesc(spuDetail.getSkuSimpleDesc() + attribute.getAttributeName() + " ");
        }
        //如果选择了颜色（款式），未选择尺寸
        if(condition.getColorAttributeOptionId() != null && condition.getSkuId() == null){
            spuDetail.setSkuStyleCode(condition.getSkuStyleCode());
            for(ProductAttributeOptionVO colorOption : colorOptionList){
                if(condition.getColorAttributeOptionId().equals(colorOption.getId())){
                    spuDetail.setSkuSimpleDesc(colorOption.getOptionValue());
                    colorOption.setSelected(1);
                    break;
                }
            }
        }
        //如果选择了sku
        if(condition.getSkuId() != null){
            spuDetail.setSkuId(condition.getSkuId());
            //未确定存在此sku前，回显库存为0
            spuDetail.setSkuStock(0L);
            //查询单个sku
            ProductSkuPriceVO skuPrice = null;
            for(ProductSkuPriceVO sku : skuList){
                if(condition.getSkuId().equals(sku.getSkuId())){
                    skuPrice = sku;
                    break;
                }
            }
            //存在此sku时
            if(skuPrice != null){
                //设置此sku的回显库存
                spuDetail.setSkuStock(skuPrice.getStock());
                //默认选择颜色的属性值
                for(ProductAttributeOptionVO colorOption : colorOptionList){
                    if(skuPrice.getColorOptionId().equals(colorOption.getId())){
                        spuDetail.setSkuSimpleDesc(colorOption.getOptionValue());
                        colorOption.setSelected(1);
                        break;
                    }
                }
                //默认选择尺码的属性值
                for(ProductAttributeOptionVO sizeOption : sizeOptionList){
                    if(skuPrice.getSizeOptionId().equals(sizeOption.getId())){
                        spuDetail.setSkuSimpleDesc(spuDetail.getSkuSimpleDesc() + " " + sizeOption.getOptionValue());
                        sizeOption.setSelected(1);
                        break;
                    }
                }
            }
        }

        return spuDetail;
    }

    @Override
    public List<ProductQueryWithCategoryVO> findProductQueryWithCategoryList() {
        List<ProductQueryWithCategoryVO> result = new ArrayList<>();

        Map<Long,ProductQueryWithCategoryVO> resultMap  = findProductCategoryMap();
        //过滤掉所有的一级分类下  二级分类挂靠商品之和为空的 一级分类
        for (ProductQueryWithCategoryVO query : resultMap.values()) {
            if (query.getCountNum() != null) {
                query.setCategoryList(query.getCategoryList().stream().sorted(Comparator.comparing(ProductCategoryTwoWithSpuNumVO::getSort)).collect(Collectors.toList()));
                result.add(query);
            }
        }
        return result.stream().sorted(Comparator.comparing(ProductQueryWithCategoryVO::getSort)).collect(Collectors.toList());
    }

    /**
     * 查询出所有的一二级分类对应的MAP集合
     * @return
     */
    private Map<Long,ProductQueryWithCategoryVO> findProductCategoryMap(){
        //查询出所有一级，返回一个map对象，key是一级id，value是一级本身
        ProductCategory productCategory = new ProductCategory();
        productCategory.setLevel((byte) 1);
        Map<Long,ProductQueryWithCategoryVO> resultMap  = productCategoryMapper.selectByModelMap(productCategory);
        //查出所有的二级集合，带着改二级下面有多少个spu数量的
        List<ProductCategoryTwoWithSpuNumVO> spuNumList = productSpuCategoryMapper.selectCategoryTwoSpuNum();

        //
        for (ProductCategoryTwoWithSpuNumVO categoryTwoWithSpuNumVO : spuNumList) {
            Long parentId = categoryTwoWithSpuNumVO.getParentId();
            if (resultMap.containsKey(parentId)) {
                //获取该一级下面的二级分类List
                List<ProductCategoryTwoWithSpuNumVO> categoryList = resultMap.get(parentId).getCategoryList();
                if (categoryList == null) {
                    categoryList = new ArrayList<>();
                }
                categoryList.add(categoryTwoWithSpuNumVO);
                resultMap.get(parentId).setCategoryList(categoryList);

                //获取该一级下面挂靠的所有spu数量
                Integer countNum = resultMap.get(parentId).getCountNum();
                if (countNum == null) {
                    countNum = 0;
                }
                countNum += categoryTwoWithSpuNumVO.getCountNum();
                resultMap.get(parentId).setCountNum(countNum);
            }
        }
        return resultMap;
    }

    @Override
    public ProductFilterVO getProductFilterList() {
        ProductFilterVO result = new ProductFilterVO();

        //二级分类
        Map<Long,ProductQueryWithCategoryVO> resultMapOld = findProductCategoryMap();
        Map<Long,List<ProductCategoryTwoWithSpuNumVO>> resultMapNew = new HashMap<>(16);
        //过滤掉所有的一级分类下  二级分类挂靠商品之和为空的 一级分类
        for (ProductQueryWithCategoryVO query : resultMapOld.values()) {
            if (query.getCountNum() != null) {
                resultMapNew.put(query.getId(),query.getCategoryList());
            }
        }
        resultMapNew.put(0L,new ArrayList<>());

        //所有颜色集合，ID为固定值
        List<ProductAttributeOption> colorAttributeOptionList = productAttributeOptionMapper.selectAttributeOptionByAttributeId(1001L);
        //所有尺寸集合，ID为固定值
        List<ProductAttributeOption> sizeAttributeOptionList = productAttributeOptionMapper.selectAttributeOptionByAttributeId(1002L);
        //构造返参
        result.setCategoryListMap(resultMapNew);
        result.setColorAttributeOptionList(colorAttributeOptionList);
        result.setSizeAttributeOptionList(sizeAttributeOptionList);
        return result;
    }

    @Override
    public List<ProductDocument> findProductListWithCondition(ProductListQueryCondition condition) {
        ProductSearchParam param = new ProductSearchParam();
        //复制条件参数
        BeanUtils.copyProperties(condition,param);
        //查询当前用户的渠道以及价格方案
        CustomerDistributorTypeAndChannelVO channelVO = customerServiceClient.getCustomerChannelById(condition.getCustomerId()).getDataWithException();
        //登录用户的渠道价格方案
        Long priceProgramId = channelVO == null ? null : channelVO.getPriceTypeId();
        //如果没有价格，提示用户“敬请期待”
        if(priceProgramId == null){
            throw new BusinessException(BusinessCode.CODE_800601);
        }
        param.setPriceProgramId(priceProgramId);
        SearchResult<ProductDocument> data = productSearchClient.search(param).getDataWithException();
        return data.getHits();
    }
    @Override
    public List<ProductBrand> findAllBrand() {
        return productBrandMapper.selectAllBrand();
    }

    @Override
    public Boolean operateProducPriceAndInfo() {
        Boolean flag;

        ProductSpu model = new ProductSpu();
        model.setSaleStatus(1);
        model.setStatus(1);
        List<ProductSpu> spus = productSpuMapper.selectByModel(model);


        logger.info("更新：操作es数据开始--------");
        List<ProductVO> productVOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(spus)){
            for (ProductSpu spu : spus) {
                ProductSaveOrUpdateCondition cond = new ProductSaveOrUpdateCondition();
                Long spuId = spu.getId();
                cond.setSpuId(spuId);
                cond.setOpType("2");
                ProductVO vo = this.toSave(cond);
                List<ProductTag> selectedTagList = vo.getProductTagList().stream().filter(v -> v.getSelected() == 1).collect(Collectors.toList());
                vo.setProductTagList(selectedTagList);

                List<ProductAttributeVO> productAttributeList = vo.getProductAttributeList();
                productAttributeList.forEach(attr -> {
                    List<ProductAttributeOptionVO> optionList = attr.getAttributeOptionList();
                    List<ProductAttributeOptionVO> selectedOptionList = optionList.stream().filter(o -> o.getSelected() == 1).collect(Collectors.toList());
                    attr.setAttributeOptionList(selectedOptionList);
                });

                ProductPriceSpu productPriceSpu = new ProductPriceSpu();
                productPriceSpu.setSpuId(spuId);
                List<ProductPriceSpu> productPriceSpus = productPriceSpuMapper.selectByModel(productPriceSpu);
                vo.setProductPriceSpuList(productPriceSpus);

                ProductPriceSku productPriceSku = new ProductPriceSku();
                productPriceSku.setSpuId(spuId);
                List<ProductPriceSku> productPriceSkus = productPriceSkuMapper.selectByModel(productPriceSku);
                vo.setProductPriceSkuList(productPriceSkus);

                //给es的SalesVolume是最终销量（初始化销量+真实销量）
                for (int j = 0; j < vo.getProductSkuList().size(); j++) {
                    vo.getProductSkuList().get(j).setSalesVolume(vo.getProductSkuList().get(j).getInitSalesVolume()+vo.getProductSkuList().get(j).getSalesVolume());
                }

                productVOList.add(vo);
            }
        }

        //上架
        flag = productSearchClient.importProduct(productVOList).getDataWithException();
        return flag;
    }
}
